﻿using System;
using System.Collections.Generic;
using System.Text;

namespace EditorAutoClose
{
   public class LRU<T>
   {
      List<T> _list;

      public delegate void Eject(T t);

      public Eject OnEject { get; set; }

      public int Count
      {
         get
         {
            return _list.Count;
         }
      }

      public LRU()
      {
         _list = new List<T>();
      }

      public void Clear()
      {
         _list.Clear();
      }

      public void Add(T t)
      {
         Touch(t);
      }

      public void Remove(T t)
      {
         _list.Remove(t);
      }

      public void Touch(T t)
      {
         // Ensure the least recently touched
         // item is on the head of the list.
         _list.Remove(t);
         _list.Add(t);
      }

      public void RemoveLRU()
      {
         if (Count > 0)
         {
            T t = _list[0];
            _list.Remove(t);

            if (OnEject != null)
            {
               OnEject(t);
            }
         }
      }
   }
}
